import 'dart:async';

import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/index/index_page.dart';
import 'package:e_reception_flutter/ui/index_nav/index_nav_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/custom_length_limiting_text_input_formatter.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';

/// 验证码-编辑框
///
/// @author: zengxiangxi
/// @createTime: 1/6/21 4:58 PM
/// @specialDemand:
class LoginAuthEditAuthWidget extends StatefulWidget {

  final ValueChanged<String> loginFunc;


  final StreamController<Null> clearValueNotifier;

  const LoginAuthEditAuthWidget({Key key,this.loginFunc, this.clearValueNotifier}) : super(key: key);
  @override
  _LoginAuthEditAuthWidgetState createState() =>
      _LoginAuthEditAuthWidgetState();
}

class _LoginAuthEditAuthWidgetState extends BaseState<LoginAuthEditAuthWidget> {
  List<String> _authList = List();

  TextEditingController _authEditingController;

  StreamSubscription streamSubscription;

  @override
  void initState() {
    super.initState();
    _authEditingController = TextEditingController();
    streamSubscription = widget.clearValueNotifier.stream.listen(_clearAllText);
    _authList = List();
    _processAuthList("");
  }

  ///清空
  _clearAllText(Null a){
    _authEditingController.text="";
    _authList=null;
    setState(() {

    });
  }

  @override
  void dispose() {
    _authList?.clear();
    _authEditingController?.dispose();
    streamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 52,
      child: Stack(
        fit: StackFit.expand,
        children: <Widget>[
          _toRowWidget(),
          _toEditTextWidget(),
        ],
      ),
    );
  }

  Widget _toEditTextWidget() {
    return Opacity(
      opacity: 0,
      child: VgTextField(
        controller: _authEditingController,
        keyboardType: TextInputType.number,
        textInputAction: TextInputAction.done,
        autofocus: true,
        inputFormatters: [
          WhitelistingTextInputFormatter(RegExp("[0-9+]"))],
        onChanged: (String completeAuth) {
          if (completeAuth.length > DEFAULT_AUTH_LENGTH_LIMIT) {
            String newValue =
                completeAuth.substring(0, DEFAULT_AUTH_LENGTH_LIMIT - 1);
            if (newValue != _authEditingController.text) {
              _authEditingController.text = newValue;
            }
            return;
          }
          _processAuthList(completeAuth);
        },
      ),
    );
  }

  Widget _toRowWidget() {
    final double computerHorizontalMargin =
        ScreenUtils.screenW(context) * 46 / 375;
    return Container(
      margin: EdgeInsets.symmetric(horizontal: computerHorizontalMargin),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: List.generate(DEFAULT_AUTH_LENGTH_LIMIT, (index) {
          if (index == (_authList?.length ?? 0)) {
            return _SmallCubeWidget(statusType: _SmallCubeStatusType.ing);
          }
          if (index > (_authList?.length ?? 0)) {
            return _SmallCubeWidget(
              statusType: _SmallCubeStatusType.wait,
            );
          }
          return _SmallCubeWidget(
            statusType: _SmallCubeStatusType.complete,
            completeNum: _authList?.elementAt(index),
          );
        }),
      ),
    );
  }

  void _processAuthList(String completeAuth) {
    if (completeAuth == null || completeAuth == "") {
      _authList = List();
    } else {
      _authList = completeAuth.split("");
    }
    setState(() {});
    if((_authList?.length ?? 0) >= DEFAULT_AUTH_LENGTH_LIMIT){
      // VgToolUtils.removeAllFocus(context);
      if(widget?.loginFunc != null){
        widget.loginFunc(completeAuth);
      }
    }
  }
}

enum _SmallCubeStatusType { ing, complete, wait }

class _SmallCubeWidget extends StatelessWidget {
  final _SmallCubeStatusType statusType;

  final String completeNum;

  const _SmallCubeWidget({
    Key key,
    this.statusType = _SmallCubeStatusType.wait,
    this.completeNum,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 52,
      height: 52,
      decoration: BoxDecoration(
          color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
          borderRadius: BorderRadius.circular(4)),
      child: Center(child: _toStatusWidget() ?? Container()),
    );
  }

  Widget _toStatusWidget() {
    if (statusType == null) {
      return null;
    }
    Widget child;
    switch (statusType) {
      case _SmallCubeStatusType.ing:
        child = Container(
          width: 2,
          height: 27,
          color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        );
        break;
      case _SmallCubeStatusType.wait:
        child = Container();
        break;
      case _SmallCubeStatusType.complete:
        child = Text(
          completeNum ?? "",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
              color: Colors.white, fontSize: 25, fontWeight: FontWeight.w600),
        );
        break;
    }
    return child;
  }
}